package com.light.applet.oauth.security.jwt.custom;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 魏彪
 */
public class CustomUserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    protected static final String PRINCIPAL_KEY = "principal";

    /**
     * 重写此方法
     *
     * @param authentication an authentication representing a user
     * @return Map<String, ?>
     */
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        Map<String, Object> response = new LinkedHashMap<>(super.convertUserAuthentication(authentication));
        response.put(PRINCIPAL_KEY, authentication.getPrincipal());
        return response;
    }

    /**
     * 重写此方法
     *
     * @param map a map of user information
     * @return Authentication
     */
    public Authentication extractAuthentication(Map<String, ?> map) {
        return new UsernamePasswordAuthenticationToken(map.get(PRINCIPAL_KEY), "N/A", getAuthorities(map));
    }

    private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
        if (!map.containsKey(AUTHORITIES)) {
            return null;
        }
        Object authorities = map.get(AUTHORITIES);
        if (authorities instanceof String) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
        }
        if (authorities instanceof Collection) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
                    .collectionToCommaDelimitedString((Collection<?>) authorities));
        }
        throw new IllegalArgumentException("Authorities must be either a String or a Collection");
    }

}
